package org.firefly.fx.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.firefly.fx.bean.TUser;
import org.firefly.fx.constants.ConfigInfo;
import org.firefly.fx.service.user.IUserService;
import org.firefly.fx.util.MatchUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(value="/user")
public class UserController {
	@Autowired IUserService userService;
	
	@RequestMapping(value="/register", method = RequestMethod.POST)
	public String register(HttpServletRequest request, HttpServletResponse response, Model model) {
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String nickName = request.getParameter("nickName");
		String mobile = request.getParameter("mobile");
		
		String msg = null;
		if(StringUtils.isBlank(email)) msg = "邮箱不能为空！";
		else if(StringUtils.isBlank(password)) msg = "密码不能为空！";
		else if(StringUtils.isBlank(nickName)) msg = "昵称不能为空！";
		else if(StringUtils.isBlank(mobile)) msg = "电话不能为空！";
		else if(MatchUtil.isEmail(email)) msg = "邮箱格式不正确！";
		else if(MatchUtil.isMobile(mobile)) msg = "手机格式不正确！";
		if(msg != null){
			model.addAttribute("msg", msg);
			return "regist";
		}
		TUser user = new TUser();
		user.setEmail(email);
		user.setPassword(password);
		user.setNickName(nickName);
		user.setMobile(mobile);
		
		userService.insert(user);
		if(user.getId()>0){
//			request.getSession().setAttribute(ConfigInfo.USER_ID, user.getId());
			return "login";
		}else{
			model.addAttribute("msg", "注册失败！");
			return "regist";
		}
	}


	@RequestMapping(value="/login")
	public String login(HttpServletRequest request , HttpServletResponse response , Model model){
		String username = request.getParameter("username");
		String password = request.getParameter("password");
	
		//TODO msg ->i18n
		if(StringUtils.isBlank(username) || StringUtils.isBlank(password)){
			model.addAttribute("msg", "用户名&密码不可为空");
			return "login";
		}
		
		TUser user = userService.login(username, password);
		if(user==null){
			model.addAttribute("msg", "用户名或密码不正确");
			return "login";
		}
		
		request.getSession().setAttribute(ConfigInfo.USER_ID, username);
		return "redirect:/main";
	}

}
